package com.merge.queue;

import com.merge.pojo.Data;
import com.merge.pojo.SliceFile;

import java.util.HashMap;
import java.util.Map;

public class SliceQueueManger {

    private  static Map<String, SliceQueue<Data>> sliceQueueMap = new HashMap<>();


    /**
     * 添加queue
     * @param file
     * @return
     */
    public static boolean addSliceQueueMap(SliceFile file) {
        SliceQueue<Data> queue = new SliceQueue<>(file);
        if (sliceQueueMap.containsKey(queue.getName())) {
            System.out.println("queue:" + queue.getName() + "已存在");
            return false;
        }
        sliceQueueMap.put(queue.getName(), queue);
        return true;
    }

    /**
     *
     * @param name
     * @return
     */
    public static SliceQueue<Data> getQueueForName(String name) {
        if (!sliceQueueMap.containsKey(name)) {
            System.out.println("queue:" + name + "不存在");
            return null;
        }
        return sliceQueueMap.get(name);
    }

    public static SliceQueue<Data>[] sliceQueueMapToArr() {
        if (sliceQueueMap.isEmpty()) return null;
        SliceQueue<Data>[] sliceQueues = new SliceQueue[sliceQueueMap.size()];
        sliceQueueMap.values().toArray(sliceQueues);
        return sliceQueues;
    }

    /**
     * 所有队列数据都为空
     * @return
     */
    public static boolean empty() {
        boolean empty = true;
        SliceQueue<Data>[] queues = sliceQueueMapToArr();
        for (SliceQueue<Data> queue: queues
             ) {
            if (queue.getSize() != 0) {
                empty = false;
                break;
            }
        }
        return empty;
    }

    public static Data[] allSliceQueuePollOne() {
        if (sliceQueueMap.isEmpty()) return null;
        Data[] values = new Data[sliceQueueMap.size()];
        SliceQueue<Data>[] queues = sliceQueueMapToArr();
        for (int i = 0; i < queues.length; i++) {
            Data data = queues[i].poll();
            if (data != null) {
                values[i] = data;
            }
        }
        return values;
    }
}
